package com.h4313.ghome.ui.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.h4313.ghome.GHomeApplication;
import com.h4313.ghome.R;
import com.h4313.ghome.io.AvailableSourcesTask;
import com.h4313.ghome.io.AvailableSourcesTask.AvailableSourcesCallback;
import com.h4313.ghome.model.Capteur;
import com.h4313.ghome.ui.NewModuleCreation;
import com.h4313.ghome.ui.adapters.CapteursAdapter;
import com.h4313.ghome.ui.dialog.AccountPickerDialog;
import com.h4313.ghome.ui.dialog.AccountPickerDialog.AccountPickerCallback;
import com.h4313.ghome.ui.dialog.HourPickerDialog;
import com.h4313.ghome.ui.dialog.HourPickerDialog.MorningConf;
import com.h4313.ghome.ui.dialog.HourPickerDialog.TimePickerCallback;
import com.h4313.ghome.utils.UIUtils;

public class CreateMorningConfFragment extends Fragment implements
		OnClickListener, AccountPickerCallback, TimePickerCallback,
		AvailableSourcesCallback {

	private static final String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/calendar";
	protected static final String TAG = CreateMorningConfFragment.class
			.getSimpleName();

	protected TextView mAccountPicker;
	protected TextView mCoffee, mGCalendar;
	protected View mCurrentPicking;
	MorningConf mConf = new MorningConf();
	private NewModuleCreation mCreation;
	private View mWait;

	private Account mPickedAccount = null;

	private Spinner mSpinner;
	private MenuItem mCreateItem;

	private final static String MODULE_NAME = "name";

	public static CreateMorningConfFragment newInstance(String name) {
		CreateMorningConfFragment frag = new CreateMorningConfFragment();
		Bundle bundle = new Bundle();
		bundle.putString(MODULE_NAME, name);
		frag.setArguments(bundle);
		return frag;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_create_morning_conf,
				container, false);

		mSpinner = (Spinner) view.findViewById(R.id.sp_actionneur_prise);
		mSpinner.setEnabled(false);

		mAccountPicker = (TextView) view.findViewById(R.id.tv_pickup_account);
		mAccountPicker.setOnClickListener(this);

		
		mCoffee = (TextView) view.findViewById(R.id.ed_defaut_cafe);
		mCoffee.setOnClickListener(this);
		
		mGCalendar = (TextView) view.findViewById(R.id.ed_defaut_heure_lecture);
		mGCalendar.setOnClickListener(this);
		

		
		mWait = view.findViewById(R.id.sp_wait);

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		AvailableSourcesTask task = new AvailableSourcesTask(this,
				getActivity());
		String moduleName = getArguments().getString(MODULE_NAME);
		task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, GHomeApplication.SERVER_URL + "/modules/" + moduleName
				+ "/sources");
	}

	@Override
	public void onAvailableSourcesFound(HashMap<String, List<Capteur>> capteurs) {

		if (getActivity() == null || isDetached()) {
			return;
		}
		
		// remove the progressBar for data has been retrieved...
		mWait.setVisibility(View.GONE);
		// ...and then process the data

		ArrayList<Capteur> items = new ArrayList<Capteur>();

		for (String type : capteurs.keySet()) {
			if ("outlet".equals(type)) {
				if (capteurs.get(type).isEmpty()) {
					// no capteur is available for the specified
					// type. A pop-up is shown, advising the
					// user
					AlertDialog.Builder builder = new AlertDialog.Builder(
							getActivity());
					builder.setPositiveButton("OK",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// nothing to do. User
									// clicked "OK", OK ?
								}
							});
					builder.setMessage(String.format(
							getResources().getString(
									R.string.no_capteur_available), type));
					builder.setTitle(R.string.no_capteur_available_title);
					builder.create().show();
				} else {
					mSpinner.setEnabled(true);
					for (Capteur c : capteurs.get(type)) {
						// format capteurs informations to suit the
						// spinner
						items.add(c);
					}
					CapteursAdapter adapter = new CapteursAdapter(getActivity(),
						items);
					mSpinner.setAdapter(adapter);
				}
			}
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		if (!(activity instanceof NewModuleCreation)) {
			throw new RuntimeException(
					"activity must implement NewModuleCreation");
		} else {
			mCreation = (NewModuleCreation) activity;
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_pickup_account:

			AccountPickerDialog dialog = new AccountPickerDialog(this);
			dialog.show(getFragmentManager(), "account_picker");
			break;

		case R.id.ed_defaut_cafe:
			DialogFragment newFragment = new HourPickerDialog(this);
			newFragment.show(getFragmentManager(), "timepicker_coffee");
			mCurrentPicking = v;
			break;

		case R.id.ed_defaut_heure_lecture:
			DialogFragment newFragment2 = new HourPickerDialog(this);
			newFragment2.show(getFragmentManager(), "timepicker_gcalendar");
			mCurrentPicking = v;
			break;
		}
	}

	@Override
	public void onAccountPicked(Account account) {
		mPickedAccount = account;
		mAccountPicker.setText(mPickedAccount.name);
		if (mSpinner.isEnabled()) {
			// both google account and required capteur has been chosen. Module
			// can be added
			mCreateItem.setEnabled(true);
		}
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.fragment_create_morning_conf, menu);
		// disabled until all required fields are filled in
		mCreateItem = menu.findItem(R.id.menu_create_morning_conf);
		mCreateItem.setEnabled(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.menu_create_morning_conf:
			getAuthToken();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1337 && resultCode == Activity.RESULT_OK) {
			getAuthToken();
		}
	}

	@Override
	public void onTimeSet(int hour, int min) {
		if (mCurrentPicking == mCoffee) {

			mConf.hourCoffee = hour;
			mConf.minCoffee = min;
			mCoffee.setText(UIUtils.formatHour(hour, min));

			mCurrentPicking = null;
		} else if (mCurrentPicking == mGCalendar) {

			mConf.hourGCalendar = hour;
			mConf.minGCalendar = min;
			mGCalendar.setText(UIUtils.formatHour(hour, min));

			mCurrentPicking = null;
		}

	}

	private void getAuthToken() {

		if (mPickedAccount == null) {
			// moins terrible que de disable le bouton ...
			UIUtils.showToast(this, "Choisissez un compte google avant",
					Toast.LENGTH_SHORT);
			return;
		}

		AccountManager accountManager = AccountManager.get(getActivity());

		accountManager.getAuthToken(mPickedAccount, AUTH_TOKEN_TYPE, null,
				getActivity(), new AccountManagerCallback<Bundle>() {

					public void run(AccountManagerFuture<Bundle> future) {
						try {

							Bundle result = future.getResult();

							Intent launch = (Intent) result
									.get(AccountManager.KEY_INTENT);
							if (launch != null) {
								startActivityForResult(launch, 1337);
								return;
							}

							// If the user has authorized your application to
							// use the calendar API
							// a token is available.
							String token = future.getResult().getString(
									AccountManager.KEY_AUTHTOKEN);
							// Now you can use the Tasks API...
							Log.d(TAG, "token = " + token);
							createModule(token);
							// useTasksAPI(token);
						} catch (OperationCanceledException e) {
							// TODO: The user has denied you access to the API,
							// you should handle that
						} catch (Exception e) {

						}
					}
				}, null);

	}

	private void createModule(String token) {
		Map<String, String> params = new HashMap<String, String>();
		// TODO

		params.put("coffee_min", String.valueOf(mConf.minCoffee));
		params.put("coffee_hour", String.valueOf(mConf.hourCoffee));
		params.put("gcalendar_min", String.valueOf(mConf.minGCalendar));
		params.put("gcalendar_hour", String.valueOf(mConf.hourGCalendar));
		params.put("token", token);
		params.put("outlet", String.valueOf(((Capteur) mSpinner
				.getSelectedItem()).getIdCapteur()));

		mCreation.createModule("morning", params);
	}

}
